package com.tsunami.utils;


import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsunami.model.PagePlus;

/**
 * 分页工具
 *
 * @author lx
 */
public class PageUtils {
    PageUtils() {

    }

    /**
     * 当前记录起始索引
     */
    public static final String PAGE_NUM = "pageNum";

    /**
     * 每页显示记录数
     */
    public static final String PAGE_SIZE = "pageSize";

    /**
     * 排序列
     */
    public static final String ORDER_BY_COLUMN = "orderByColumn";

    /**
     * 排序的方向 "desc" 或者 "asc".
     */
    public static final String IS_ASC = "asc";

    /**
     * 排序的方向 "desc".
     */
    public static final String ORDER_DESC = "desc";
    /**
     * 排序的方向 "asc".
     */
    public static final String ORDER_ASC = "asc";

    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 每页显示记录数 默认值 默认查全部
     */
    public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;

    /**
     * 构建 plus 分页对象
     *
     * @param <T> domain 实体
     * @param <K> vo 实体
     * @return 分页对象
     */
    public static <T, K> PagePlus<T, K> buildPagePlus() {
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM, DEFAULT_PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE, DEFAULT_PAGE_SIZE);
        String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN);
        String isAsc = ServletUtils.getParameter(IS_ASC);
        PagePlus<T, K> page = new PagePlus<>(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderByColumn)) {
            String orderBy = SQLUtil.escapeOrderBySql(orderByColumn);
            if (ORDER_ASC.equals(isAsc)) {
                page.addOrder(OrderItem.asc(orderBy));
            } else if (ORDER_DESC.equals(isAsc)) {
                page.addOrder(OrderItem.desc(orderBy));
            }
        }
        return page;
    }

    /**
     * 构建 MP 普通分页对象
     *
     * @param <T> domain 实体
     * @return 分页对象
     */
    public static <T> Page<T> buildPage() {
        Integer pageNum = ServletUtils.getParameterToInt(PAGE_NUM, DEFAULT_PAGE_NUM);
        Integer pageSize = ServletUtils.getParameterToInt(PAGE_SIZE, DEFAULT_PAGE_SIZE);
        String orderByColumn = ServletUtils.getParameter(ORDER_BY_COLUMN);
        String isAsc = ServletUtils.getParameter(IS_ASC);
        Page<T> page = new Page<>(pageNum, pageSize);
        if (StringUtils.isNotBlank(orderByColumn)) {
            String orderBy = SQLUtil.escapeOrderBySql(orderByColumn);
            if (ORDER_ASC.equals(isAsc)) {
                page.addOrder(OrderItem.asc(orderBy));
            } else if (ORDER_DESC.equals(isAsc)) {
                page.addOrder(OrderItem.desc(orderBy));
            }
        }
        return page;
    }
}
